<template>
  <div class="background-image-container" ref="imageContainer" :style="{ backgroundPosition: `${transitionCoordinates.x}px ${transitionCoordinates.y}px` }">
    <div class="login" ref="login">
      <header class="header">爱的智慧树管理系统</header>
      <el-input placeholder="请输入账号" v-model="from.userName" clearable>
      </el-input>
      <el-input placeholder="请输入密码" v-model="from.password" show-password>
      </el-input>
      <div class="code">
        <el-input placeholder="请输入验证码" v-model="from.code" class="code-inp"></el-input>
        <el-image class="code-image" :src="codeImageUrl" @click="change"></el-image>
      </div>
      <el-button type="primary" style="margin-top: 20px" @click="login"
        >登录</el-button
      >
    </div>
  </div>
</template>

<script>
import { getloginCaptcha, userLogin } from '@/api/login'
import { mapMutations } from 'vuex'

export default {
  data () {
    return {
      from: {
        userName: '',
        password: '',
        codeKey: '',
        code: ''
      },
      codeImageUrl: '',
      targetCoordinates: {
        x: 0,
        y: 0
      },
      transitionCoordinates: {
        x: -256,
        y: -147
      },
      movementFactor: 300, // 可根据实际情况调整移动敏感度，这里设为300作为示例
      dampenFactor: 200, // 可调整阻尼系数，用于控制收敛速度，示例设为200
      animationFrameId: null // 用于存储 requestAnimationFrame 返回的ID
    }
  },
  methods: {
    ...mapMutations('user', ['setLogin']),
    login () {
      if (this.userName === '' || this.password === '') {
        this.$message({
          message: '账号和密码不能为空',
          type: 'warning'
        })
        return
      }

      userLogin(this.from)
        .then((data) => {
          console.log(data)
          if (data.code === 0) {
            this.$message.error(data.msg)
          } else if (data.code === 1) {
            localStorage.setItem('token', data.data)
            this.setLogin(true)
            this.$message({
              message: '登录成功',
              type: 'success'
            })
            this.$router.push({
              path: '/home'
            })
          }
        })
        .catch((error) => {
          this.setLogin(false)
          console.log(error)
        })
    },
    // setCenterCoordinates () {
    //   this.getBackgroundImageSize().then((bgImgSize) => {
    //     this.centerCoordinates.x = -1 * Math.abs(bgImgSize.width - this.$refs.imageContainer.clientWidth) / 1
    //     this.centerCoordinates.y = -1 * Math.abs(bgImgSize.height - this.$refs.imageContainer.clientHeight) / 1
    //     this.targetCoordinates.x = this.centerCoordinates.x
    //     this.targetCoordinates.y = this.centerCoordinates.y
    //     this.transitionCoordinates.x = this.centerCoordinates.x
    //     this.transitionCoordinates.y = this.centerCoordinates.y
    //   })
    // },
    // getBackgroundImageSize () {
    //   return new Promise((resolve) => {
    //     const img = new Image()
    //     img.src = require('../image/bg-logo.jpg') // 替换为实际的本地图片路径，这里假设放在项目的 assets 目录下，根据实际情况调整路径
    //     img.onload = () => {
    //       resolve({
    //         width: img.width,
    //         height: img.height
    //       })
    //     }
    //   })
    // },
    // bindMouseMoveEvent () {
    //   const imageContainer = this.$refs.imageContainer
    //   imageContainer.addEventListener('mousemove', (e) => {
    //     const width = this.movementFactor / imageContainer.clientWidth
    //     const height = this.movementFactor / imageContainer.clientHeight
    //     const cursorX = e.pageX - (window.innerWidth / 2)
    //     const cursorY = e.pageY - (window.innerHeight / 2)
    //     this.targetCoordinates.x = width * cursorX * -1 + this.centerCoordinates.x
    //     this.targetCoordinates.y = height * cursorY * -1 + this.centerCoordinates.y
    //     if (!this.animationFrameId) { // 新增判断，避免重复调用
    //       this.updateBackgroundPosition()
    //     }
    //   })
    // },
    // updateBackgroundPosition () {
    //   console.log('Updating background position...')
    //   this.transitionCoordinates.x += ((this.targetCoordinates.x - this.transitionCoordinates.x) / this.dampenFactor)
    //   this.transitionCoordinates.y += ((this.targetCoordinates.y - this.transitionCoordinates.y) / this.dampenFactor)
    //   this.$refs.imageContainer.style.backgroundPosition = `${this.transitionCoordinates.x}px ${this.transitionCoordinates.y}px`
    //   // 使用 requestAnimationFrame 来在下一帧继续更新背景图位置，实现平滑过渡效果
    //   this.animationFrameId = requestAnimationFrame(() => this.updateBackgroundPosition())
    // },
    // cancelAnimationFrame () {
    //   if (this.animationFrameId) {
    //     cancelAnimationFrame(this.animationFrameId)
    //   }
    // }
    bindMouseMoveEvent () {
      const imageContainer = this.$refs.imageContainer
      imageContainer.addEventListener('mousemove', (e) => {
        const width = this.movementFactor / imageContainer.clientWidth
        const height = this.movementFactor / imageContainer.clientHeight
        const cursorX = e.pageX - (window.innerWidth / 2)
        const cursorY = e.pageY - (window.innerHeight / 2)
        this.targetCoordinates.x = width * cursorX * -1 - 256 // 初始位置基于CSS默认样式，这里设为0
        this.targetCoordinates.y = height * cursorY * -1 - 147 // 初始位置基于CSS默认样式，这里设为0
        if (!this.animationFrameId) { // 新增判断，避免重复调用
          this.updateBackgroundPosition()
        }
      })
    },
    updateBackgroundPosition () {
      this.transitionCoordinates.x += ((this.targetCoordinates.x - this.transitionCoordinates.x) / this.dampenFactor)
      this.transitionCoordinates.y += ((this.targetCoordinates.y - this.transitionCoordinates.y) / this.dampenFactor)
      // 使用 requestAnimationFrame 来在下一帧继续更新背景图位置，实现平滑过渡效果
      this.animationFrameId = requestAnimationFrame(() => this.updateBackgroundPosition())
    },
    cancelAnimationFrame () {
      if (this.animationFrameId) {
        cancelAnimationFrame(this.animationFrameId)
      }
    },
    change () {
      getloginCaptcha().then(data => {
        this.codeImageUrl = data.data.img
        this.from.codeKey = data.data.key
      })
    }
  },
  mounted () {
    // this.setCenterCoordinates()
    // this.bindMouseMoveEvent()
    this.bindMouseMoveEvent()
  },
  beforeUnmount () {
    this.cancelAnimationFrame()
  },
  beforeDestroy () {
    window.removeEventListener('mousemove', this.handleMouseMove) // 避免内存泄漏
  },
  created () {
    getloginCaptcha().then(data => {
      console.log(data)
      this.codeImageUrl = data.data.img
      this.from.codeKey = data.data.key
    })
  }
}
</script>

<style scoped>
.background-image-container {
  width: 100vw;
  height: 100vh;
  background-image: url('../image/bg-logo.jpg');
  background-size: 150% auto;
  background-position: -256px -147px;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  position: relative;
}

.background-image-container::before {
  content: '';
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  background: linear-gradient(135deg, rgba(0,0,0,0.4) 0%, rgba(0,0,0,0.2) 100%);
  z-index: 1;
}

.login {
  width: 400px;
  margin-right: 10%;
  padding: 2.5rem;
  background: rgba(255, 255, 255, 0.15);
  backdrop-filter: blur(10px);
  border-radius: 16px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  z-index: 2;
  animation: slideIn 0.6s ease-out;
}

@keyframes slideIn {
  from {
    opacity: 0;
    transform: translateX(30px);
  }
  to {
    opacity: 1;
    transform: translateX(0);
  }
}

.header {
  text-align: center;
  font-size: 1.8rem;
  font-weight: 600;
  color: #fff;
  margin-bottom: 2rem;
  text-shadow: 0 2px 4px rgba(0,0,0,0.2);
}

.el-input {
  margin-bottom: 1.2rem;
}

.el-input :deep(.el-input__inner) {
  height: 45px;
  background: rgba(255, 255, 255, 0.9);
  border: none;
  border-radius: 8px;
  font-size: 1rem;
  color: #333;
  transition: all 0.3s ease;
}

.el-input :deep(.el-input__inner):focus {
  background: rgba(255, 255, 255, 1);
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

.code {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1.2rem;
}

.code-inp {
  flex: 1;
  margin-right: 1rem;
}

.code-image {
  width: 120px;
  height: 45px;
  border-radius: 8px;
  cursor: pointer;
  transition: transform 0.3s ease;
}

.code-image:hover {
  transform: scale(1.02);
}

.el-button {
  width: 100%;
  height: 45px;
  font-size: 1.1rem;
  border-radius: 8px;
  background: var(--primary-color);
  border: none;
  transition: all 0.3s ease;
}

.el-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
}

@media screen and (max-width: 768px) {
  .login {
    width: 90%;
    margin: 0 auto;
    padding: 2rem;
  }

  .header {
    font-size: 1.5rem;
  }

  .el-input :deep(.el-input__inner) {
    height: 40px;
  }

  .code-image {
    width: 100px;
    height: 40px;
  }

  .el-button {
    height: 40px;
    font-size: 1rem;
  }
}

@media screen and (max-width: 480px) {
  .login {
    padding: 1.5rem;
  }

  .header {
    font-size: 1.3rem;
    margin-bottom: 1.5rem;
  }
}
</style>
